package com.potato369.cryptNacos.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@Api(tags = "CryptController", consumes = "Nacos加解密管理")
@Slf4j
@RestController
public class CryptController {

    private StringEncryptor encryptor;

    @Autowired
    public void setEncryptor(StringEncryptor encryptor) {
        this.encryptor = encryptor;
    }

    @ApiOperation("Nacos加密")
    @PostMapping("/encrypt")
    public String encrypt(@ApiParam(name = "加密字符") @RequestParam(name = "encrypt") String encrypt) {
        if (Objects.isNull(encrypt) || encrypt.length() == 0) {
            return "加密失败，需要加密的字符串不能为空。";
        }
        log.info("需要加密的字符串 = {}", encrypt);
        return "ENC(" + encryptor.encrypt(encrypt) + ")";
    }

    @ApiOperation("Nacos解密")
    @PostMapping("/decrypt")
    public String decrypt(@ApiParam(name = "解密字符") @RequestParam(name = "decrypt") String decrypt) {
        if (Objects.isNull(decrypt) || decrypt.length() == 0) {
            return "解密失败，需要解密的字符串不能为空。";
        }
        decrypt = decrypt.replace("ENC(", "").replace(")", "").trim();
        log.info("需要解密的字符串 = {}", decrypt.trim());
        return encryptor.decrypt(decrypt.trim());
    }
}
